package com.lightspring.core.io;

import cn.hutool.core.lang.Assert;
import com.lightspring.beans.BeansException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
 * URl资源加载方式
 * @author 毅航
 * @date 2023/11/5 16:19
 */
public class UrlResource implements Resource {

    private final URL url;

    public UrlResource(URL url) {
        Assert.notNull(url,"URL must not be null");
        this.url = url;
    }

    /**
     * @author: yihang
     * @description: 从对应url处获取相关内容
     * 大致相关逻辑：构建连接，然后获取流，返回流信息，对于异常信息进行捕获处理
     * @date: 22/11/5 16:16
     * @parms
     * @return
     */
    @Override
    public InputStream getInputStream() throws IOException {

        URLConnection con = this.url.openConnection();
        try {
            return con.getInputStream();
        }
        catch (IOException ex){
            if (con instanceof HttpURLConnection){
                ((HttpURLConnection) con).disconnect();
            }
            throw ex;
        }
    }

    @Override
    public boolean exists() {
        URLConnection con ;
        try {
            // 此处只做简单判断，只要资源可以连接就认为资源存在
            con = this.url.openConnection();
            if (con != null) {
                return true;
            }
        }catch (IOException ex) {
            // 出现异常
            throw new BeansException("Url does not exist");
        }
        return false;
    }
}
